<template>
  <el-drawer :model-value="modelValue" :title="drawerTitle" :size="1000" :close-on-click-modal="false" destroy-on-close
    :before-close="handleBeforeClose" @update:model-value="handleDrawerClose">
    <div v-loading="detailLoading" class="relative h-full">
      <div class="h-full" v-loading="loading && mode === 'edit'">
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="auto">
          <div class="flex mb-[2px]">
            <el-form-item :label="$t('competition.agreementName')" prop="agreementName" class="flex-1 mr-10 ml-5">
              <el-input v-model="formData.agreementName" :placeholder="$t('competition.pleaseInput')" class="w-[364px]" maxlength="50" />
            </el-form-item>
            <div class="flex-1"></div>
          </div>
          <el-form-item :label="$t('competition.agreementContent')" prop="agreementContent" class="ml-5 mb-5">
            <div :class="['w-full', showContentError ? 'border border-red-500 rounded' : '']">
              <WangEditor
                v-model="formData.agreementContent"
                mode="default"
                :scrollable="true"
                :height="'calc(100vh - 200px)'"
                :placeholder="$t('competition.pleaseInputContent')"
              />
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <template #footer>
      <div class="flex justify-end gap-3">
        <el-button @click="handleCancel">{{ $t('common.cancelTxt') }}</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading" class="w-20">
          {{ $t('common.confirm') }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import { $t } from '@vben/locales'
import WangEditor from '#/components/editor.vue'
import deleteIcon from '#/assets/images/delete-icon.png'
import { isWangEditorEmpty, getWangEditorTextLength } from '#/utils/editorUtils'
import { createMatchAgreementApi, getMatchAgreementApi } from '#/api/competition/competition-list'
import { convertObsUrlsToKeys, convertKeysToObsUrls } from '#/utils/getImgUrl';

// 类型定义
interface Props {
  modelValue: boolean
  formData: any
  mode: 'add' | 'edit'
}

interface FormData {
  id?: string
  matchId: string
  agreementName: string
  agreementContent: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: ['preserve']
  cancel: []
}>()

// 引用
const formRef = ref<FormInstance>()

// 响应式数据
const formData = ref<FormData>({
  matchId: '',
  agreementName: '',
  agreementContent: '',
})
const originalFormData = ref<FormData>({} as FormData)
const showContentError = ref(false)
const detailLoading = ref(false)
const loading = ref(false)
const isProcessing = ref(false)
const isSuccessClose = ref(false)

// 计算属性
// const drawerTitle = computed(() =>
//   props.mode === 'add' ? $t('competition.addAgreementTitle') : $t('competition.editAgreementTitle')
// )
const drawerTitle = ref($t('competition.addAgreementTitle'))
const agreementId = ref('')

const isFormChanged = computed(() =>
  JSON.stringify(formData.value) !== JSON.stringify(originalFormData.value)
)

// 表单验证规则
const rules = ref<FormRules>({
  agreementName: [
    { required: true, message: $t('competition.pleaseInputAgreementName'), trigger: 'blur' },
    { min: 1, max: 50, message: $t('competition.lengthShouldBe1To50'), trigger: 'blur' },
  ],
  agreementContent: [
    {
      required: true,
      validator: (_: any, value: string, callback: Function) => {
        if (isWangEditorEmpty(value)) {
          showContentError.value = true;
          callback(new Error($t('competition.pleaseInputAgreementContent')));
        } else {
          // 检查字符长度是否超过12000
          const textLength = getWangEditorTextLength(value);
          if (textLength > 12000) {
            showContentError.value = true;
            callback(new Error($t('announcement.validation.contentTooLong')));
          } else {
            showContentError.value = false;
            callback();
          }
        }
      },
      trigger: 'change',
    },
  ],
})

// 初始化表单数据
const initFormData = (data: any) => {
  return {
    // id: data?.id,
    matchId: data?.matchId || data?.id, // 兼容从列表行传入 id
    agreementName: data?.agreementName || null,
    agreementContent: data?.agreementContent || null,
  }
}

// 监听props数据变化
watch(() => props.modelValue, async (val) => {
  if (!val) return

  // 初始化表单
  formData.value = initFormData(props.formData)
  originalFormData.value = JSON.parse(JSON.stringify(formData.value))
  isProcessing.value = false
  isSuccessClose.value = false

  // 无数据但有 matchId，查询协议详情
  if (!props.formData?.agreementName && formData.value.matchId) {
    detailLoading.value = true
    try {
      const res: any = await getMatchAgreementApi({ matchId: formData.value.matchId })
      if (res) {
        if (res.agreementName) drawerTitle.value = $t('competition.editAgreementTitle')
        formData.value.agreementName = res.agreementName || ''
        // 将内容中的OBS URL转换为key值
        formData.value.agreementContent = await convertKeysToObsUrls(res.agreementContent || '')
        originalFormData.value = JSON.parse(JSON.stringify(formData.value))
        agreementId.value = res.id || ''
        // 移除 console.log 调试语句
      }
    } catch (e) {
      // 移除 console.error 调试语句
    } finally {
      detailLoading.value = false
    }
  }
})

// 事件处理函数
const handleDrawerClose = (value: boolean) => {
  emit('update:modelValue', value)
}

// API调用
const submitForm = async () => {
  // 将内容中的OBS URL转换为key值
  formData.value.agreementContent = await convertObsUrlsToKeys(formData.value.agreementContent)
  const param = JSON.parse(JSON.stringify(formData.value))
  param.status = 1
  if (props.mode === 'edit') param.id = agreementId.value
  await createMatchAgreementApi(param)

  ElMessage.success(props.mode === 'add' ? $t('competition.addSuccessShort') : $t('competition.updateSuccessShort'))
  isSuccessClose.value = true
  emit('update:modelValue', false)
  emit('success', 'preserve')
}

// 确定按钮事件
const handleConfirm = async () => {
  if (!formRef.value) {
    ElMessage.warning($t('competition.incompleteInfo'))
    return
  }

  try {
    await formRef.value.validate()
    loading.value = true
    isProcessing.value = true
    await submitForm()
  } catch (e) {
    // 移除 console.error 调试语句
  } finally {
    loading.value = false
    isProcessing.value = false
  }
}

// 显示确认退出对话框
const showExitConfirm = async (): Promise<boolean> => {
  try {
    await ElMessageBox.confirm('', {
      title: '',
      message: `
        <div style="display: flex; align-items: center;">
          <img src="${deleteIcon}" style="width: 48px; height: 48px; margin-right: 10px;" />
          <span>${$t('competition.dataNotSavedConfirmExit')}</span>
        </div>
      `,
      confirmButtonText: $t('competition.yes'),
      cancelButtonText: $t('competition.no'),
      customClass: 'delete-dialog',
      dangerouslyUseHTMLString: true,
      center: false,
      distinguishCancelAndClose: true,
    })
    return true // 用户选择"是"，确认退出
  } catch (error) {
    return false // 用户选择"否"或关闭对话框，不退出
  }
}

// 检查是否可以关闭
const checkCanClose = async (): Promise<boolean> => {
  if (isProcessing.value) return false

  // 如果表单有修改且不是成功关闭，显示确认对话框
  if (isFormChanged.value && !isSuccessClose.value) {
    return await showExitConfirm()
  }

  return true // 无修改，可以直接关闭
}

// 重置表单状态
const resetFormState = () => {
  isProcessing.value = false
  loading.value = false
  formRef.value?.resetFields()
}

// 处理抽屉关闭前的检查
const handleBeforeClose = async (done: () => void) => {
  try {
    const canClose = await checkCanClose()
    if (canClose) {
      resetFormState()
      emit('cancel')
      done()
    }
  } catch (error) {
    // 移除 console.error 调试语句
    resetFormState()
    emit('cancel')
    done()
  }
}

// 取消按钮事件
const handleCancel = async () => {
  try {
    const canClose = await checkCanClose()
    if (canClose) {
      resetFormState()
      emit('update:modelValue', false)
      emit('cancel')
    }
  } catch (error) {
    // 移除 console.error 调试语句
    resetFormState()
    emit('update:modelValue', false)
    emit('cancel')
  }
}
</script>
